//
//  HOnePageDetailViewController.m
//  ShowYork
//
//  Created by hxh on 2020/10/4.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "CampusVlogDetailViewController.h"
#import "CampusVlogDetailCell.h"
#import "ZFCustomControlView.h"
#import "HomePageFeedbackView.h"
#import "RPAppShareView.h"
#import "AppDelegate.h"

#import "UserInfoFollowModel.h"
#import "MineFollowItemModel.h"

@interface CampusVlogDetailViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,CampusVlogDetailCellDelegate>

@property (nonatomic,strong)ZFPlayerController *player; /// 视频播放器
@property (nonatomic,strong)ZFCustomControlView *fullControlView; /// 视频播放视图
@property (nonatomic,strong)UITableView *tableView; /// 列表


@property (nonatomic,strong)NSMutableArray *dataArray; /// 列表数据


@property (nonatomic,strong)CampusVlogDetailCell *currentVideoCell; /// 当前播放的视频cell



@property (nonatomic,assign)BOOL isShow; /// 是否展示状态栏


@property (nonatomic,strong)NSNumber *schId;
@property (nonatomic,assign)NSInteger currentIndex; /// 当前对象的分页索引
@property (nonatomic,strong)NSNumber *playStatus; /// 播放状态


@property (nonatomic,strong)CampusSchoolVideoItemModel *currentModel;

@property (nonatomic,strong)UIView *toolView;

@property (nonatomic,strong)UIButton *backButton;
@property (nonatomic,strong)UIImageView *backImageView;

@property (nonatomic,strong)UIButton *moreButton;

@property (nonatomic,strong)UIImageView *moreImageView;

@property (nonatomic,assign)BOOL isLastPage;

@property (nonatomic,strong)NSURLSessionTask *task;


@property (nonatomic,copy)NSString *schoolName;


@property (nonatomic,assign)BOOL isDraging;
@property (nonatomic,assign)BOOL isUpdateProgress;

@end

@implementation CampusVlogDetailViewController


- (void)viewWillAppear:(BOOL)animated{
    
    
    [super viewWillAppear:animated];
    
    if (self.playStatus.intValue != 2) {
        [self.player.currentPlayerManager play];
    }else{
        [self.player.currentPlayerManager pause];
    }
    self.player.viewControllerDisappear = NO;
    
    [IQKeyboardManager sharedManager].enable = NO;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = NO;
  
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [self updatePlayerStatus];
    [self.player.currentPlayerManager pause];
    self.player.viewControllerDisappear = YES;
    
    [MobClick endLogPageView:@"HomePageDetail"];
    [IQKeyboardManager sharedManager].enable = YES;

    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    

    
}

- (ZFCustomControlView *)fullControlView {
    if (!_fullControlView) {
        _fullControlView = [[ZFCustomControlView alloc] init];
    }
    return _fullControlView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.pagingEnabled = YES;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.scrollsToTop = NO;
        _tableView.backgroundColor = RGBA(20, 24, 36, 1);
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.frame = self.view.bounds;
        _tableView.rowHeight = _tableView.frame.size.height;
    }
    return _tableView;
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    @zf_weakify(self)
    [self.player zf_filterShouldPlayCellWhileScrolled:^(NSIndexPath *indexPath) {
        @zf_strongify(self)
        [self playTheVideoAtIndexPath:indexPath scrollAnimated:NO];
    }];
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (instancetype)initWithConfigInfo:(NSDictionary *)configInfo{
    if (self = [super init]) {
        
        [self.dataArray addObjectsFromArray:configInfo[@"listSource"]];
        
        self.currentIndex = [configInfo[@"currentIndex"] intValue];
        self.schId = configInfo[@"schoolId"];
        self.isLastPage = [configInfo[@"lastPage"]boolValue];
        self.schoolName = configInfo[@"schoolName"];
        self.currentModel = self.dataArray[self.currentIndex];
    
    }
    return self;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isHideNavBar = YES;
    
    [self setNormalData];
}

- (void)setNormalData{
    [self setUI];
    [self registNote];
}

- (void)setUI{
    
    self.isUpdateProgress = YES;
    
    [self.view addSubview:self.tableView];
    [self.tableView reloadData];
    /// playerManager
    ZFAVPlayerManager *playerManager = [[ZFAVPlayerManager alloc] init];
    self.player = [ZFPlayerController playerWithScrollView:self.tableView playerManager:playerManager containerViewTag:100];
    self.player.disableGestureTypes = ZFPlayerDisableGestureTypesPan | ZFPlayerDisableGestureTypesPinch;
    self.player.controlView = self.fullControlView;
    self.player.allowOrentitaionRotation = NO;
    self.player.WWANAutoPlay = YES;
    __weak typeof(self)weakSelf = self;
    // 赋值修改播放视频文本框隐藏的bug
    self.player.notification.willResignActive = ^(ZFPlayerNotification * _Nonnull registrar) {
        if (weakSelf.player.viewControllerDisappear) return;
        if (weakSelf.player.pauseWhenAppResignActive && weakSelf.player.currentPlayerManager.isPlaying) {
            weakSelf.player.pauseByEvent = YES;
        }
        weakSelf.player.orientationObserver.lockedScreen = YES;
        if (!weakSelf.player.pauseWhenAppResignActive) {
            [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
            [[AVAudioSession sharedInstance] setActive:YES error:nil];
        }
    };

    @zf_weakify(self)
    /// 更新另一个控制层的时间
    self.player.playerPlayTimeChanged = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, NSTimeInterval currentTime, NSTimeInterval duration) {
        @zf_strongify(self)
        if (!self.isDraging && self.isUpdateProgress) {
            [self.currentVideoCell updateProgressValue:self.player.progress];
        }
    };
    self.player.playerDidToEnd = ^(id  _Nonnull asset) {
        @zf_strongify(self)
        if (!self.player.viewControllerDisappear) {
            [self.player.currentPlayerManager replay];
        }
    };
    
    /// 停止的时候找出最合适的播放(只能找到设置了tag值cell)
    self.player.zf_scrollViewDidEndScrollingCallback = ^(NSIndexPath * _Nonnull indexPath) {
        @zf_strongify(self)
        if (!self.player.playingIndexPath) {
            [self playTheVideoAtIndexPath:indexPath scrollAnimated:NO];
        }
    };

    self.player.zf_playerShouldPlayInScrollView = ^(NSIndexPath * _Nonnull indexPath) {
        @zf_strongify(self)
        if ([indexPath compare:self.player.playingIndexPath] != NSOrderedSame) {
            [self playTheVideoAtIndexPath:indexPath scrollAnimated:NO];
        }
    };
    
    self.fullControlView.controlViewAppearedCallback = ^(BOOL appeared) {

    };
    self.fullControlView.controlViewPlayerStatusCallback = ^(BOOL status) {
        @zf_strongify(self)
        [self updatePlayerStatus];
    };
    
    self.tableView.backgroundColor = UIColor.blackColor;
  
    self.view.backgroundColor =  UIColor.blackColor;
    
    [self.tableView setContentOffset:CGPointMake(0, kScreenH * self.currentIndex)];
    

    self.isHideNavBar = YES;
    
    
    self.toolView = [[UIView alloc]init];
    [self.view addSubview:self.toolView];
    
    [self.toolView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(GK_STATUSBAR_HEIGHT);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(44);
    }];
    
    self.moreImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"campus_report_tag"]];
    [self.toolView addSubview:self.moreImageView];
    [self.moreImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.toolView);
        make.right.equalTo(self.toolView).offset(-16);
    }];
    
    self.moreButton = [[UIButton alloc]init];
    [self.moreButton addTarget:self action:@selector(moreMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.toolView addSubview:self.moreButton];
    [self.moreButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.bottom.equalTo(self.toolView);
        make.width.mas_equalTo(100);
    }];
    
    self.backImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"common_back_normal_tag"]];
    [self.toolView addSubview:self.backImageView];
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.toolView);
        make.left.equalTo(self.toolView).offset(16);
    }];
    
    self.backButton = [[UIButton alloc]init];
    [self.backButton addTarget:self action:@selector(backMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.toolView addSubview:self.backButton];
    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.equalTo(self.toolView);
        make.width.mas_equalTo(100);
    }];
    

    if (self.currentIndex <= self.dataArray.count - 2 && !self.isLastPage) {
        [self loadRequestData];
    }
}

- (void)backMethod{
    

    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 处理通知
- (void)registNote{
    
}


#pragma mark - network

- (void)updateShareCountSource{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = self.currentModel.id;
    param[@"md5"] = [RPAppManager md5StrWithApi:UpdateVlogShareNum];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(UpdateVlogShareNum) parames:param success:^(id responseObj) {
        
        int shareNum = self.currentModel.shareNum.intValue;
        shareNum++;
        self.currentModel.shareNum = @(shareNum);
        
        [self.tableView reloadData];

    } failure:^(id error) {

    }];
}

- (void)loadRequestData{
    
    if (self.task != nil && self.task.state == NSURLSessionTaskStateRunning) {
        [self.task cancel];
    }
    if (self.isLastPage) {
        return;
    }
    
    NSInteger page = ceil(self.dataArray.count/10.0f) + 1;
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:SchoolVlogList];
    param[@"pageIndex"] = @(page);
    param[@"pageSize"] = @(10);
    param[@"id"] = self.schId;
    param[@"userId"] = [RPAppManager getCustomerId];
    self.task = [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(SchoolVlogList) parames:param success:^(id responseObj) {
        
 
        
        [self.dataArray addObjectsFromArray:[CampusSchoolVideoItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]]];
        
        if ([responseObj[RESPONSE][LASTPAGE]boolValue]) {
            self.isLastPage = YES;
        }
        [self.tableView reloadData];
        
    } failure:^(id error) {
    
    }];
}


- (void)doDissOrLikeWithStatus:(BOOL)status{
    
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }

    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"type"] = status?@1:@2;
    param[@"postId"] = self.currentModel.id;

    if (status) {
        param[@"isTourist"] = self.currentModel.isLike?@1:@2;
    }else{
        param[@"isTourist"] = self.currentModel.isUnLike?@1:@2;
    }
    param[@"evaluateType"] = @(7);

    param[@"md5"] = [RPAppManager md5StrWithApi:DoDetailLike];
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(DoDetailLike) parames:param success:^(id responseObj) {
        
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
        if (status) {
            NSInteger likeNum = self.currentModel.likeNum.intValue;
            if (self.currentModel.isLike) {
                likeNum--;
            }else{
                likeNum++;
            }
            self.currentModel.likeNum = @(likeNum);
            self.currentModel.isLike = !self.currentModel.isLike;
        }else{
            NSInteger unLikeNum = self.currentModel.unLikeNum.intValue;
            if (self.currentModel.isUnLike) {
                unLikeNum--;
            }else{
                unLikeNum++;
            }
            self.currentModel.unLikeNum = @(unLikeNum);
            self.currentModel.isUnLike = !self.currentModel.isUnLike;
        }
        
        [self.tableView reloadRow:self.currentIndex inSection:0 withRowAnimation:UITableViewRowAnimationNone];
    }];
}


#pragma mark - method

- (void)removeAllHelpView{

}

- (void)removeHelpView{
    
}

- (void)removeMethod{
    
    [self.player stopCurrentPlayingView];
    
    [self.navigationController popViewControllerAnimated:YES];

}

- (void)moreMethod{
    __weak typeof(self)weakSelf = self;
    HomePageFeedbackView *feedbackView = [[HomePageFeedbackView alloc]initWithCompleteBlock:^{
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":weakSelf.navigationController} completion:nil];
    }else{
        [MGJRouter openURL:@"local://ddup/report" withUserInfo:@{@"navigationVC":weakSelf.navigationController,@"reportId":weakSelf.currentModel.id ,@"reportType":@(0)} completion:nil];
    }
    }];
    
    [feedbackView show];
}

#pragma mark - tableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CampusVlogDetailCell *cell = [CampusVlogDetailCell cellWithTableView:tableView];
    [cell setModel:self.dataArray[indexPath.item]];
    cell.delegate = self;
    return cell;
}

//#pragma mark - HomePageDetailVideoItemCellDelegate
- (void)videoItemLikeWithCurrentModel:(CampusSchoolVideoItemModel *)currentModel{
    self.currentModel = currentModel;
    [self doDissOrLikeWithStatus:YES];
}
- (void)videoItemDissWithCurrentModel:(CampusSchoolVideoItemModel *)currentModel{
    self.currentModel = currentModel;
    [self doDissOrLikeWithStatus:NO];
}
- (void)videoItemUpdateProgressValue:(CGFloat)value{
    self.isDraging = NO;
    @zf_weakify(self)
    [self.player seekToTime:self.player.totalTime*value completionHandler:^(BOOL finished) {
        @zf_strongify(self)
        if (finished) {
            self.isUpdateProgress = YES;
        }
    }];
}
- (void)videoItemBeginDraging{
    self.isDraging = YES;
    self.isUpdateProgress = NO;
}
- (void)videoItemChangeProgressValue:(CGFloat)value{
    
}

- (void)videoItemShareWithCurrentModel:(CampusSchoolVideoItemModel *)currentModel{
    [self commonShareWithCurrentModel:currentModel];
}

#pragma mark - UIScrollViewDelegate   列表播放必须实现

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    [scrollView zf_scrollViewDidEndDecelerating];
    NSInteger index = scrollView.contentOffset.y/kScreenH;
    if (index != self.currentIndex) {
        self.currentIndex = index;
    }
    self.playStatus = @0;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [scrollView zf_scrollViewDidScroll];
    int index = scrollView.contentOffset.y/kScreenH;
    if (index == self.dataArray.count - 3 && !self.isLastPage) {
        if (self.task != nil && self.task.state == NSURLSessionTaskStateRunning) {
            [self.task cancel];
        }else{
            [self loadRequestData];
        }
      
    }
    if (index == self.dataArray.count - 1 && !self.isLastPage) {
        if (self.task != nil && self.task == NSURLSessionTaskStateRunning) {
            return;
        }
        [self loadRequestData];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [scrollView zf_scrollViewDidEndDraggingWillDecelerate:decelerate];
    NSInteger index = scrollView.contentOffset.y/kScreenH;
    if (scrollView.contentOffset.y <= 0) {
        [WHToast showMessage:@"已是第一个" duration:2 finishHandler:nil];
        return;
    }
    if (index == self.dataArray.count - 1 && self.isLastPage) {
        [WHToast showMessage:@"没有更多了" duration:2 finishHandler:nil];
    }
}

- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView {
    [scrollView zf_scrollViewDidScrollToTop];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.playStatus = @0;
    [scrollView zf_scrollViewWillBeginDragging];
}
#pragma mark - ZFTableViewCellDelegate

- (void)zf_playTheVideoAtIndexPath:(NSIndexPath *)indexPath {
    [self playTheVideoAtIndexPath:indexPath scrollAnimated:NO];
}

#pragma mark - private method
/// play the video
- (void)playTheVideoAtIndexPath:(NSIndexPath *)indexPath scrollAnimated:(BOOL)animated {

//
    if (self.playStatus.intValue == 2) {
        return;
    }

    if (self.player.currentPlayerManager.playState == ZFPlayerPlayStatePaused) {
        [self.player.currentPlayerManager play];
        return;
    }
    if (self.player.currentPlayerManager.playState == ZFPlayerPlayStatePlaying) {
        return;
    }

    CampusSchoolVideoItemModel *model = self.dataArray[indexPath.item];
    
    [self.fullControlView coverURLString:model.cover fullScreenMode:ZFFullScreenModeLandscape appeared:NO];

    self.currentVideoCell = [self.tableView cellForRowAtIndexPath:indexPath];

    if (animated) {
        [self.player playTheIndexPath:indexPath assetURL:[NSURL URLWithString:model.url] scrollPosition:ZFPlayerScrollViewScrollPositionTop animated:YES];
    } else {
        [self.player playTheIndexPath:indexPath assetURL:[NSURL URLWithString:model.url]];
    }
}


//#pragma mark - 分享统一方法
- (void)commonShareWithCurrentModel:(CampusSchoolVideoItemModel *)itemModel{
    if ([RPAppManager isShowNetworkView]) {
        [WHToast showErrorWithMessage:@"网络好像有点问题，请检查后重试" duration:2 finishHandler:nil];
        return;
    }
    [RPAppShareView showCompleteblock:^(XHShareViewPlatformType platformType) {
        UMSocialPlatformType type = UMSocialPlatformType_UnKnown;
        switch (platformType) {
            case XHShareViewPlatformTypeWeChatSession:
                type = UMSocialPlatformType_WechatSession;
                break;
            case XHShareViewPlatformTypeWeChatMoments:
                type = UMSocialPlatformType_WechatTimeLine;
                break;
            case XHShareViewPlatformTypeQQ:
                type = UMSocialPlatformType_QQ;
                break;

            case XHShareViewPlatformTypeQQZone:
                type = UMSocialPlatformType_Qzone;
                break;

            case XHShareViewPlatformTypeQQWeibo:
                type = UMSocialPlatformType_Sina;
                break;
            default:
                break;
        }
        if (![[UMSocialManager defaultManager] isInstall:type]) {
            if (type == UMSocialPlatformType_WechatSession || type == UMSocialPlatformType_WechatTimeLine) {
                [WHToast showMessage:@"请先安装微信" duration:2 finishHandler:nil];
            }
            if (type == UMSocialPlatformType_QQ || type == UMSocialPlatformType_Qzone) {
                [WHToast showMessage:@"请先安装QQ" duration:2 finishHandler:nil];
            }
            if (type == UMSocialPlatformType_Sina) {
                [WHToast showMessage:@"请先安装微博" duration:2 finishHandler:nil];
            }
            return;
        }
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];

        NSString *title = itemModel.title.length == 0?self.schoolName:itemModel.title;


        NSDictionary *infoPlist = [[NSBundle mainBundle] infoDictionary];

        NSString *icon = [[infoPlist valueForKeyPath:@"CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles"] lastObject];

        UIImage *shareImage= [UIImage imageNamed:icon];

        
        //创建网页内容对象
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:@"" thumImage:shareImage];
        //设置网页地址
        shareObject.webpageUrl = [NSString stringWithFormat:@"%@dynamic?vlogId=%@",HtmlUrl,itemModel.id];
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:type messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            if (error) {
                UMSocialLogInfo(@"************Share fail with error %@*********",error);
            }else{

            }
        }];
        [self updateShareCountSource];
    }];
}

- (void)updatePlayerStatus{
    if (self.player.currentPlayerManager.isPlaying) {
        self.playStatus = @(1);
    }else{
        self.playStatus = @(2);
    }
}

- (void)dealloc{
    
}

@end
